package com.example.interceptor;

import com.alibaba.fastjson.JSON;
import com.example.pojo.entity.JobSeeker;
import com.example.util.JWTUtils;
import com.example.vo.Result;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @author 小岁
 * @version 2023/10/1 22:08
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //发送ajax请求，将本地存储中的token放到headers中
        System.out.println("========");
        String token = request.getHeader("token");
        String userId = request.getHeader("id");
        System.out.println(token);
        System.out.println(userId);

        //判断token合法性
        if (null!=token&&!token.equals("null")&&redisTemplate.hasKey("js_"+userId)){
            String redisToken = (String) redisTemplate.opsForValue().get("js_"+userId);
            if (redisToken.equals(token)){
                redisTemplate.expire("js_"+userId,1, TimeUnit.HOURS);
                return true;
            }
        }else if (null!=token&&!token.equals("null")&&redisTemplate.hasKey("jr_"+userId)){
            String redisToken = (String) redisTemplate.opsForValue().get("jr_"+userId);
            if (redisToken.equals(token)){
                redisTemplate.expire("jr_"+userId,1, TimeUnit.HOURS);
                return true;
            }
        }else{
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.print(JSON.toJSONString(new Result(500,"请先登录!")));
            return false;
        }
        return false;
    }
}
